package com.googlecode.javaeeutils.jpa.manager;

import java.util.ArrayList;
import java.util.List;

import com.googlecode.javaeeutils.jpa.EntityWithNaturalKey;

public class OneToManyListMerger {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static synchronized <ENTITY extends EntityWithNaturalKey> List<ENTITY> mergeLists(List<ENTITY> existing, List<ENTITY> newItems) {
        if (newItems == null) {
            return existing;
        }
        if (existing == null) {
            existing = new ArrayList<ENTITY>();
        }
        if (existing == newItems) {
            return existing;
        }
        for (ENTITY entity : newItems) {
            ENTITY savedEntity = (ENTITY) entity.findByNaturalKey();
            if (existing.contains(savedEntity)) {
                existing.get(existing.indexOf(savedEntity)).copyFrom(entity);
            } else {
                if (savedEntity != null) {
                    savedEntity.copyFrom(entity);
                    existing.add(savedEntity);
                } else {
                    entity.linkMasterData();
                    existing.add(entity);
                }
            }
        }
        return existing;
    }

}
